/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package BLL;


import DAL.ConnectData;
import DTO.Product;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;


/**
 *
 * @author Vien-IT
 */
public class BProduct {
    
    ConnectData condata ;

    public BProduct() {
        condata = new ConnectData();
    }
    
   public ArrayList<Product> getAll(String sql)
   {
       ArrayList<Product> products = new ArrayList<Product>(   );
       Product product = null;
       try {
           ResultSet rs = condata.executeQuery(sql);
           while(rs.next())
           {
               product = new Product();
               product.setProductId(rs.getInt("productId"));
               product.setName(rs.getString("name"));
               product.setInfo(rs.getString("info"));
               product.setImge(rs.getString("image"));
               product.setPrice(rs.getString("price"));
               product.setCategoryId(rs.getInt("categoryId"));
               product.setNumberOfProduct(rs.getLong("numberOfProduct"));
               product.setBestSale(rs.getLong("bestSale"));
               products.add(product);
               
           }
           condata.close();
       } catch (Exception e) {
           System.out.println(e);
       }
       
       return products.isEmpty() ? null : products;
   }
   
   
   public ArrayList<Product> getAll()
   {
       String sql = "select * from tblProduct";
       return this.getAll(sql);
   }
   
   public Product getById(int productId)
   {
       String sql = "select * from tblProduct where productId = "+productId+"";
       ArrayList<Product> products = this.getAll(sql);
       return products == null ? null : products.get(0);
   }
   
   public ArrayList<Product> getByCategoryId(int categoryId)
   {
       String sql = "select * from tblProduct where categoryId = "+categoryId+"";
       return getAll(sql);
   }
   
  public  boolean insert(Product product)
   {
       product.setDateCreate(new Date());
       boolean check = false;
        try {
            
            String sql = "insert into tblProduct(name,info,image,price,categoryId,numberOfProduct,bestSale)"
                    + "values ('"+product.getName()+"','"+product.getInfo()+"','"+product.getImge()+"','"+product.getPrice()+"',"
                    + ""+product.getCategoryId()+","+product.getNumberOfProduct()+","+product.getBestSale()+" ) ";
            int rs = condata.executeUpdate(sql);
            if(rs > 0)
                check = true;
        } catch (Exception ex) {
            System.out.println(ex);
        }
        return check ;
   }
    
}
